package com.jyh.controller;

import com.jyh.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${jyh.path}")
    private String basePath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //log.info("file:{}",file.toString());
        //log.info("basePath:{}"+basePath);

        //后缀名
        String type = file.getOriginalFilename();
        type=type.substring(type.lastIndexOf("."));

        //文件名
        String fileName = UUID.randomUUID().toString()+type;

        //判断文件路径是否存在，不存在新建路径
        File dir=new File(basePath);
        if(!dir.exists()){
            dir.mkdirs();
        }

        //将file另存
        try {
            file.transferTo(new File(basePath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(fileName);
    }


    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){

        try {
            //从response获取输出流
            ServletOutputStream outputStream = response.getOutputStream();

            //新建输入流，读取对应name的文件
            FileInputStream inputStream=new FileInputStream(new File(basePath+name));

            //设置响应格式
            response.setContentType("image/jpg");
            //将输入流写道输出流
            int len=0;
            byte [] bytes=new byte[1024];
            while ((len=inputStream.read(bytes))!=-1){
                outputStream.write(bytes);
            }
            //关闭流
            inputStream.close();
            outputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
